<?php


namespace app\admin\controller;


use app\admin\model\LiveSettingModel;
use app\admin\model\RoleUserModel;
use app\admin\model\UserModel;
use app\admin\model\WechatSettingModel;
use app\common\model\ApplyLiveModel;
use app\common\model\CompanyModel;
use app\common\model\EnvelopesReceiveModel;
use app\common\model\LiveAccountModel;
use app\common\model\LiveLotteryModel;
use app\common\model\PushShutoffCallbackLogModel;
use app\common\model\RedEnvelopesModel;
use app\common\model\WechatUserModel;
use app\user\controller\AssetController;
use cmf\controller\AdminBaseController;
use think\Db;
use think\Validate;

class LiveController extends AdminBaseController
{
    protected $admin_id;   // 登录的用户id
    protected $role_id;    // 登录用户的角色
    protected $company_id; // 登录用户的公司id

    public function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        $admin_id = cmf_get_current_admin_id();
        $role_id = RoleUserModel::where('user_id', $admin_id)->value('role_id');
        $role_id = $role_id ? $role_id : 1;
        $this->admin_id = $admin_id;
        $this->role_id = $role_id;

        $user_info = UserModel::get($admin_id);
        $this->company_id = $user_info['company_id'];

//        $where = [
//            'end_time' => ['<', time()]
//        ];
//        Db::name('apply_live')->where($where)->setField('is_overdue', 1);
    }

    /**
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @auther 时光浅暖
     * @date 2020/2/6 8:50
     */
    public function setting()
    {
        $admin_id = $this->admin_id;
        $role_id = $this->role_id;
        $this->assign('role_id', $role_id);
        if ($this->request->isAjax()) {
            $user_info = UserModel::get($admin_id);
            $setting = LiveSettingModel::where('company_id', $user_info['company_id'])->find();

            // @author 时光浅暖

            $data = $this->request->param();
            $where = [];
            $page = 1;
            if (isset($data['page'])) {
                $page = $data['page'];
            }

            if (isset($data['name'])) {
                $id = CompanyModel::where('name', 'like', '%' . $data['name'] . '%')->value('id');
                $where['company_id'] = $id;
            }

            if ($role_id == 3) {
                $where['company_id'] = $user_info['company_id'];
            }

            $list = LiveAccountModel::with(['company'])->where($where)->paginate(15, false, ['page' => $page]);

            $this->success('', null, [
                'list' => $list,
                'setting' => $setting,
                'role_id' => $role_id
            ]);
        }
        return $this->fetch();
    }

    /**
     * @auther 时光浅暖
     * @date 2020/2/6 8:49
     */
    public function operation_account()
    {
        $data = $this->request->param();

        if ($data['id'] == '') {
            //新增
            $find = LiveAccountModel::get(['user_login' => $data['user_login']]);
            if ($find) {
                $this->error('账号已被使用！');
            }

            $account = new LiveAccountModel();
            $account->user_login = $data['user_login'];
            $account->user_pass = cmf_password($data['user_pass']);
            $account->company_id = $this->company_id;
            $account->save();
            $this->success('添加成功！');
        } else {
            //修改
            $account = LiveAccountModel::get($data['id']);
            $account->user_pass = cmf_password($data['user_pass']);
            $account->company_id = $this->company_id;
            $result = $account->save();
            if ($result === false) {
                $this->error('修改失败！');
            }
            $this->success('修改成功！');
        }
    }

    public function updateSetting()
    {
        if ($this->request->isPost()) {
            $data = $this->request->param();
            $admin_id = cmf_get_current_admin_id();
            $user_info = UserModel::get($admin_id);
            if (isset($data['id']) && $data['id']) {
                $setting = LiveSettingModel::get($data['id']);
            } else {
                $setting = new  LiveSettingModel();
            }
            if ($user_info['company_id']) {
                $setting->company_id = $user_info['company_id'];
            } else {
                $setting->company_id = $data['company_id'];
            }
            $setting->AccessKeyID = $data['AccessKeyID'];
            $setting->AccessKeySecret = $data['AccessKeySecret'];
            $setting->pull_key = $data['pull_key'];
            $setting->push_key = $data['push_key'];
            $setting->pull_address = $data['pull_address'];
            $setting->push_address = $data['push_address'];
            $res = $setting->save();
            if ($res) {
                $this->success('更新成功');
            } else {
                $this->error('更新失败');
            }
        }
    }

    /**
     * @return mixed
     * @throws \think\exception\DbException
     * @auther 时光浅暖
     * @date 2020/2/6 9:08
     */
    public function room_list()
    {
        $admin_id = $this->admin_id;
        $role_id = $this->role_id;
        $this->assign('role_id', $role_id);
        if ($this->request->isAjax()) {
            $data = $this->request->param();
            $user_info = UserModel::get($admin_id);
            $where = [];
            $page = 1;
            if (isset($data['page'])) {
                $page = $data['page'];
            }

            if ($data['theme'] != '') {
                $where[] = ['theme', 'like', '%' . $data['theme'] . '%'];
            }

            if ($data['contact_mobile'] != '') {
                $company_id = CompanyModel::where('contact_mobile', $data['contact_mobile'])->value('id');
                $where[] = ['company_id', 'eq', $company_id];
            }

            if ($data['is_delete'] != '') {
                $where[] = ['is_delete', 'eq', $data['is_delete']];
            }

            // 发布时间
            if (!empty($data['date'])) {
                $where[] = ['create_time', 'between time', [$data['date'][0] / 1000, ($data['date'][1] / 1000) + 86400]];
            }

            if ($role_id == 3) {
                $where[] = ['company_id', 'eq', $user_info['company_id']];
            }

            $obj = ApplyLiveModel::with(['live_account', 'company'])
                ->where($where)
                ->order('create_time desc')
                ->paginate(15, false, ['page' => $page]);

            if ($obj) {
                $obj = $obj->toArray();

                foreach ($obj['data'] as $k => $v) {
                    $date1 = date('Y-m-d', $v['start_time']);
                    $date2 = date('H:i:s', $v['start_time']);
//                    $date3 = date('Y-m-d',$v['end_time']);
//                    $date4 = date('H:i:s',$v['end_time']);
                    $obj['data'][$k]['date1'] = strtotime($date1) * 1000;
                    $obj['data'][$k]['date2'] = strtotime($date2) * 1000;
//                    $obj['data'][$k]['date3'] = strtotime($date3) * 1000;
//                    $obj['data'][$k]['date4'] = strtotime($date4) * 1000;

                    $obj['data'][$k]['trailer_img'] = [$v['trailer_img']];
                }
            }

            $return = [
                'list' => $obj,
                'role_id' => $role_id
            ];

            if ($role_id == 3) {
                $return['account'] = LiveAccountModel::where('company_id', $this->company_id)->select();
            }

            $this->success('', null, $return);
        }
        return $this->fetch();
    }

    public function goodsImgUploader()
    {
        $image = \think\Image::open(request()->file('file'));
        $size = $image->size();
        $scale = 1 / 1;
//        if (($size[0]/ $size[1] != $scale)) {
//            $this->error('图片的宽高比率必须为1:1');
//        }
        if ($size[0] != 1080) {
            $this->error('图片的宽必须为1080');
        }

        if ($size[1] != 1920) {
            $this->error('图片的高必须为1920');
        }


        $assetController = new AssetController($this->request);
        $assetController->webuploader();
    }

    public function submit()
    {
        $data = $this->request->param();
        $live_account = LiveAccountModel::get($data['account_id']);

        $start_time = $data['date2'] / 1000;
//        $end_time   = $data['date4'] / 1000;
//        if ($start_time >= $end_time) {
//            $this->error('开始时间必须小于结束时间');
//        }
//        $minutes = round(($end_time - $start_time) / 60,2); // 估计 总分钟

        if (isset($data['id']) && $data['id'] != '') {
            //开始事务
            Db::startTrans();
            try {
                $liveInfo = ApplyLiveModel::get($data['id']);
                if ($liveInfo['start_time'] <= time() && $data['date2'] / 1000 != $liveInfo['start_time']) {
                    throw new \Exception('直播时间已到，时间不可以修改');
                }

                if ($data['date2'] / 1000 <= time()) {
                    throw new \Exception('直播时间必须大于当前时间');
                }


                $apply = new ApplyLiveModel;
                // 修改时的必填字段
                $sqlData = [
                    'theme' => $data['theme'],
                    'company_id' => $live_account['company_id'],
                    'account_id' => $data['account_id'],
                    'trailer_img' => $data['trailer_img'][0],
                    'start_time' => $data['date2'] / 1000,
//                    'end_time'      => $data['date4'] / 1000,
//                    'minutes'       => $minutes,
                    'online_number' => $data['online_number']
                ];
                if (!$apply->save($sqlData, ['id' => $data['id']])) {
                    throw new \Exception('修改失败!');
                }

                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error($e->getMessage());
            }

            $this->success('修改成功');

        } else {
            //开始事务
            Db::startTrans();
            try {

                if ($data['date2'] / 1000 <= time()) {
                    throw new \Exception('直播时间必须大于当前时间');
                }

                // 新增时的必填字段
                $apply = new ApplyLiveModel;
                $sqlData = [
                    'theme' => $data['theme'],
                    'company_id' => $live_account['company_id'],
                    'account_id' => $data['account_id'],
                    'trailer_img' => $data['trailer_img'][0],
                    'start_time' => $data['date2'] / 1000,
//                    'end_time'      => $data['date4'] / 1000,
//                    'minutes'       => $minutes,
                    'online_number' => $data['online_number']
                ];
                $apply->save($sqlData);
                $insert_id = $apply->id;

                // 生成 推流播流地址
                $urlArr = $this->create_url($insert_id, $insert_id);

                if (!$apply->save([
                    'pushurl' => $urlArr['pushurl'],
                    'rtmpurl' => $urlArr['rtmpurl'],
                    'flvurl' => $urlArr['flvurl'],
                    'm3u8url' => $urlArr['m3u8url'],
                ], ['id' => $insert_id])) {
                    throw new \Exception('新增失败!');
                }

                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error($e->getMessage());
            }

            $this->success('新增成功');

        }

    }

    /*
    * 生成直播推流 播流地址
    * */
    public function create_url($AppName, $StreamName)
    {
        $option = cmf_get_plugin_config('aliyun'); // 阿里云直播插件配置
        $now = time();

        //------------------- 阿里云视频直播控制台 地址生成器 鉴权设置 -----------

        //加密key，即直播后台鉴权里面自行设置

        $pull_key = $option['pull_key'];    // 播流 主key
        $push_key = $option['push_key'];    // 推流 主key
        $time = $now + 60 * 60 * 3;     // URL的有效期 180分钟 随意设定

        //------------------------ end ---------------------------------------------

        $strpush = "/{$AppName}/{$StreamName}-{$time}-0-0-{$push_key}";

        $push_cdn = $option['push_cdn'];
        $pull_cdn = $option['pull_cdn'];

        //推流地址  一个
        $pushurl = "rtmp://{$push_cdn}/{$AppName}/{$StreamName}?auth_key={$time}-0-0-" . md5($strpush);

        //播流地址
        $strviewrtmp = "/{$AppName}/{$StreamName}-{$time}-0-0-{$pull_key}";
        $strviewflv = "/{$AppName}/{$StreamName}.flv-{$time}-0-0-{$pull_key}";
        $strviewm3u8 = "/{$AppName}/{$StreamName}.m3u8-{$time}-0-0-{$pull_key}";

        $rtmpurl = "rtmp://{$pull_cdn}/{$AppName}/{$StreamName}?auth_key={$time}-0-0-" . md5($strviewrtmp);//播流地址
        $flvurl = "http://{$pull_cdn}/{$AppName}/{$StreamName}.flv?auth_key={$time}-0-0-" . md5($strviewflv);//播流地址
        $m3u8url = "http://{$pull_cdn}/{$AppName}/{$StreamName}.m3u8?auth_key={$time}-0-0-" . md5($strviewm3u8);    //播流地址

        $result = array(
            'status' => true,
            'msg' => '获取直播数据成功！',
            'pushurl' => $pushurl,
            'rtmpurl' => $rtmpurl,
            'flvurl' => $flvurl,
            'm3u8url' => $m3u8url,
        );
        return $result;
    }


    /*
     * 推流日志
     * */
    public function pushLog()
    {
        if ($this->request->isAjax()) {

            $data = $this->request->param();
            $num = 15;
            $page = 1;

            if (isset($data['page'])) {
                $page = $data['page'];
            }
            $admin_id = cmf_get_current_admin_id();
            $admin_info = UserModel::get($admin_id);
            $where = [];

            if (isset($data['theme'])) {
                $apply_live_id = ApplyLiveModel::where('theme', 'like', '%' . $data['theme'] . '%')->value('id');
                if (!$apply_live_id) {
                    $list = [];
                    $this->success('', null, $list);
                } else {
                    $where[] = ['id', 'eq', $apply_live_id];
                }
            }
            if ($admin_info['company_id']) {
                $where[] = ['company_id', '=', $admin_info['company_id']];
            }
            if (!empty($data['date'])) {
                $where[] = ['time', 'between time', [$data['date'][0] / 1000, ($data['date'][1] / 1000) + 86400]];
            }

            $list = PushShutoffCallbackLogModel::with(['applyLive' => ['company']])->where($where)->order('time desc')->paginate($num, false, ['page' => $page]);

            if ($list) {
                $list = $list->toArray();
            }
            $this->success('', null, $list);
        }

        return $this->fetch();
    }

    /*
     * 发红包日志
     * */
    public function send_red_envelopes()
    {
        if ($this->request->isAjax()) {

            $data = $this->request->param();
            $num = 15;
            $page = 1;

            if (isset($data['page'])) {
                $page = $data['page'];
            }

            $where = [];

            if (isset($data['theme'])) {
                $apply_live_ids = ApplyLiveModel::where('theme', 'like', '%' . $data['theme'] . '%')->column('id');
                if (!$apply_live_ids) {
                    $list = [];
                    $this->success('', null, $list);
                } else {
                    $where['live_id'] = array('in', $apply_live_ids);
                }
            }

            if (isset($data['mobile'])) {
                $merchant = MerchantsModel::get(['mobile' => $data['mobile']]);
                if (!$merchant) {
                    $list = [];
                    $this->success('', null, $list);
                } else {
                    $where['merchant_id'] = $merchant->id;
                    //dump($merchant->id);
                }
            }
            $admin_id = cmf_get_current_admin_id();
            $admin_info = UserModel::get($admin_id);
            if ($admin_info['company_id']) {
                $where[] = ['company_id', '=', $admin_info['company_id']];
            }
            if (!empty($data['date'])) {
                $where[] = ['create_time', 'between time', [$data['date'][0] / 1000, ($data['date'][1] / 1000) + 86400]];
            }

            $list = RedEnvelopesModel::with(['applyLive' => ['company']])
                ->withCount(['receive'])->where($where)
                ->order('create_time desc')
                ->paginate($num, false, ['page' => $page]);

            if ($list) {
                $list = $list->toArray();
            }
            $this->success('', null, $list);

        }

        return $this->fetch();
    }


    /*
     * 根据红包id获取领取记录
     * */
    public function receiveLog()
    {
        $data = $this->request->param();
        $num = 15;
        $page = 1;

        if (isset($data['page'])) {
            $page = $data['page'];
        }

        $where = [];

        if (isset($data['theme'])) {
            $apply_live_ids = ApplyLiveModel::where('theme', 'like', '%' . $data['theme'] . '%')->column('id');
            if (!$apply_live_ids) {
                $list = [];
                $this->success('', null, $list);
            } else {
                $where[] = ['live_id', 'in', $apply_live_ids];
            }
        }

        if (isset($data['member_no'])) {
            $users = WechatUserModel::get(['member_no' => $data['member_no']]);
            if ($users) {
                $where[] = ['member_id', 'eq', $users->id];
            }

            if (!$users) {
                $list = [];
                $this->success('', null, $list);
            }
        }

        if (!empty($data['date'])) {
            $where[] = ['create_time', 'between time', [$data['date'][0] / 1000, ($data['date'][1] / 1000) + 86400]];
        }

        $where[] = ['red_envelopes_id', 'eq', $data['id']];

        $list = EnvelopesReceiveModel::with(['member'])->where($where)
            ->order('create_time desc')
            ->paginate($num, false, ['page' => $page]);

        if ($list) {
            $list = $list->toArray();
        }
        $this->success('', null, $list);
    }

    /*
     * 抽奖记录
     * */
    public function lottery()
    {
        if ($this->request->isAjax()) {
            $data = $this->request->param();
            $num = 15;
            $page = 1;

            if (isset($data['page'])) {
                $page = $data['page'];
            }

            $where = [];

            if (isset($data['theme'])) {
                $apply_live_ids = ApplyLiveModel::where('theme', 'like', '%' . $data['theme'] . '%')->column('id');
                if (!$apply_live_ids) {
                    $list = [];
                    $this->success('', null, $list);
                } else {
                    $where[] = ['live_id', 'in', $apply_live_ids];
                }
            }

            if (isset($data['mobile'])) {
                $company = CompanyModel::get(['contact_mobile' => $data['mobile']]);
                if (!$company) {
                    $list = [];
                    $this->success('', null, $list);
                } else {
                    $where[] = ['company_id', 'eq', $company->id];
                    //dump($merchant->id);
                }
            }

            if (!empty($data['date'])) {
                $where[] = ['create_time', 'between time', [$data['date'][0] / 1000, ($data['date'][1] / 1000) + 86400]];
            }

            $list = LiveLotteryModel::with(['applyLive' => ['company'], 'member'])->where($where)->order('create_time')->paginate($num, false, ['page' => $page]);

            if ($list) {
                $list = $list->toArray();
            }
            $this->success('', null, $list);

        }
        return $this->fetch();
    }

}
